import 'dart:convert';

import 'package:dio/dio.dart';
import '../constants/api_constants.dart';
import '../models/translate_response.dart';
import '../app_logger.dart';

class ApiService {
  final Dio _dio = Dio(BaseOptions(
    baseUrl: ApiConstants.apiBaseUrl,
    headers: ApiConstants.headers,
    connectTimeout: const Duration(milliseconds: 30000),
    receiveTimeout: const Duration(milliseconds: 30000),
  ));

  ApiService() {
    _setupInterceptors();
  }

  void _setupInterceptors() {
    _dio.interceptors.add(LogInterceptor(
      requestBody: true,
      responseBody: true,
    ));
  }

  /// 图片翻译
  Future<ImageTranslateResponse> translateImage({
    required String imageBase64,
    String from = 'auto',
    String to = 'en',
    int pasteType = 1,
  }) async {
    try {
      // 记录请求日志
      log.d('Sending image translation request:');
      log.d('Source language: $from');
      log.d('Target language: $to');
      log.d('Paste type: $pasteType');

      final requestBody = {
        'image': imageBase64,
        'from': from,
        'to': to,
        'paste_type': pasteType,
      };

      final response = await _dio.post(
        ApiConstants.imageTranslateEndpoint,
        data: jsonEncode(requestBody),
      );

      log.d('Response status: ${response.statusCode}');
      log.d('Response data type: ${response.data.runtimeType}');

      // 检查响应格式
      if (response.data is Map<String, dynamic>) {
        final result = ImageTranslateResponse.fromJson(response.data);

        // 打印关键字段日志
        log.d('Parsed response: success=${result.success}, logId=${result.logId}');
        log.d('Has pasteImg: ${result.result.pasteImg.isNotEmpty}');

        return result;
      } else {
        log.d('Unexpected response format: ${response.data}');
        throw Exception('服务器返回格式错误');
      }
    } on DioException catch (e) {
      String errorMessage = '图片翻译失败';
      if (e.response != null && e.response!.data != null) {
        try {
          log.d('Error response: ${e.response!.data}');
          errorMessage = e.response!.data['error'] ?? errorMessage;
        } catch (_) {
          log.d('Failed to parse error response');
        }
      } else {
        log.d('Dio exception with no response: ${e.message}');
      }
      throw Exception(errorMessage);
    } catch (e) {
      log.d('Unexpected error in API service: $e');
      throw Exception('图片翻译出错: $e');
    }
  }
}